package com.app.oral.handler

import com.app.oral.dto.DialogueQuestion
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import org.apache.ibatis.type.BaseTypeHandler
import org.apache.ibatis.type.JdbcType
import org.apache.ibatis.type.MappedTypes
import java.sql.CallableStatement
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.SQLException

/**
 * 情景问答列表类型处理器，处理List<DialogueQuestion>与JSON字符串的映射
 */
@MappedTypes(List::class)
class DialogueQuestionListTypeHandler : BaseTypeHandler<List<DialogueQuestion>>() {

    private val objectMapper: ObjectMapper = jacksonObjectMapper()
    private val typeReference = object : TypeReference<List<DialogueQuestion>>() {}

    @Throws(SQLException::class)
    override fun setNonNullParameter(ps: PreparedStatement, i: Int, parameter: List<DialogueQuestion>, jdbcType: JdbcType?) {
        ps.setString(i, objectMapper.writeValueAsString(parameter))
    }

    @Throws(SQLException::class)
    override fun getNullableResult(rs: ResultSet, columnName: String): List<DialogueQuestion>? {
        val json = rs.getString(columnName)
        return parseJson(json)
    }

    @Throws(SQLException::class)
    override fun getNullableResult(rs: ResultSet, columnIndex: Int): List<DialogueQuestion>? {
        val json = rs.getString(columnIndex)
        return parseJson(json)
    }

    @Throws(SQLException::class)
    override fun getNullableResult(cs: CallableStatement, columnIndex: Int): List<DialogueQuestion>? {
        val json = cs.getString(columnIndex)
        return parseJson(json)
    }

    private fun parseJson(json: String?): List<DialogueQuestion>? {
        return if (json.isNullOrBlank() || json == "[]") {
            emptyList()
        } else {
            try {
                objectMapper.readValue(json, typeReference)
            } catch (e: Exception) {
                emptyList()
            }
        }
    }
}